Skip to main content

谈谈 forwardRef

是什么

forwardRef 为高阶组件 ,传入一个对象,传入一个函数来操作 DOM

怎么用

预览地址

import React, { forwardRef, useRef } from "react";

// 子组件 无forwardRef :报错,接受不到ref
// const Profile = (props, ref) => {
// return <h2>Profile</h2>;
// };

// 子组件 有forwardRef
const Profile = forwardRef(function (props, ref) {
return <h2 ref={ref}>Profile</h2>;
});

// 父组件
const App = () => {
const profileRef = useRef();

const printRef = () => {
console.log(profileRef.current);
};

return (
<div>
<Profile name={"lsh"} ref={profileRef} />
<button onClick={printRef}>点击</button>
</div>
);
};

export default App;

解决了什么

因为我们之前操作 dom,子组件若为函数式组件是不行的,因为它没有实例,用这个高阶组件就能完美解决这个问题

参考文章